<template>
  <div class="app-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="8">
        <el-card shadow="hover">
          <div style="display: flex; align-items: center;">
            <i class="el-icon-coin" style="font-size: 40px; color: #409EFF; margin-right: 15px;" />
            <div>
              <div style="color: #909399; font-size: 14px;">待付款总额</div>
              <div style="font-size: 24px; font-weight: bold; color: #409EFF; margin-top: 5px;">
                {{ statistics.unpaid_amount }} USD
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div style="display: flex; align-items: center;">
            <i class="el-icon-files" style="font-size: 40px; color: #E6A23C; margin-right: 15px;" />
            <div>
              <div style="color: #909399; font-size: 14px;">待付款账单数</div>
              <div style="font-size: 24px; font-weight: bold; color: #E6A23C; margin-top: 5px;">
                {{ statistics.unpaid_count }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div style="display: flex; align-items: center;">
            <i class="el-icon-check" style="font-size: 40px; color: #67C23A; margin-right: 15px;" />
            <div>
              <div style="color: #909399; font-size: 14px;">总金额</div>
              <div style="font-size: 24px; font-weight: bold; color: #67C23A; margin-top: 5px;">
                {{ statistics.total_amount }} USD
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选栏 -->
    <el-card shadow="never" style="margin-bottom: 20px;">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="listQuery.payment_status" placeholder="支付状态" clearable style="width: 100%;" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="listQuery.supplier_id" placeholder="选择供应商" clearable filterable style="width: 100%;" @change="handleFilter">
            <el-option
              v-for="supplier in suppliers"
              :key="supplier.id"
              :label="supplier.name"
              :value="supplier.id"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="listQuery.kw" placeholder="搜索订单号/供应商/交易号" clearable @keyup.enter.native="handleFilter">
            <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" icon="el-icon-plus" @click="handleCreate">创建应付账单</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 应付账单列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="基本信息" width="150">
        <template slot-scope="scope">
          <div style="line-height: 1.8;">
            <div v-if="scope.row.order_no" style="margin-bottom: 4px;">
              <el-link type="primary" style="font-size: 13px;" @click="viewOrder(scope.row.order_id)">
                {{ scope.row.order_no }}
              </el-link>
            </div>
            <div style="color: #909399; font-size: 12px;">{{ scope.row.transaction_date }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="供应商" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span style="font-weight: 500;">{{ scope.row.supplier_name || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="付款项目/类型" show-overflow-tooltip>
        <template slot-scope="scope">
          <div style="line-height: 1.6;">
            <div style="font-weight: 500;">{{ scope.row.notes || '-' }}</div>
            <div style="color: #909399; font-size: 12px;">{{ scope.row.transaction_type }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="应付金额" width="120" align="right">
        <template slot-scope="scope">
          <span style="font-weight: bold;">{{ scope.row.payable_amount || scope.row.amount }}</span>
          <span style="color: #909399; margin-left: 5px;">{{ scope.row.currency }}</span>
        </template>
      </el-table-column>

      <el-table-column label="实际支付/待支付" width="150" align="right">
        <template slot-scope="scope">
          <!-- 如果有实际支付金额 -->
          <div v-if="scope.row.amount" style="display: flex; align-items: center; justify-content: flex-end; gap: 5px;">
            <i
              v-if="scope.row.payable_amount && parseFloat(scope.row.amount) > parseFloat(scope.row.payable_amount)"
              class="el-icon-warning"
              style="color: #F56C6C;"
              title="实际支付大于应付金额"
            />
            <span
              :style="{
                fontWeight: 'bold',
                color: scope.row.payable_amount && parseFloat(scope.row.amount) === parseFloat(scope.row.payable_amount) ? '#67C23A' : (scope.row.payable_amount ? '#F56C6C' : '#409EFF')
              }"
            >
              {{ scope.row.amount }}
            </span>
          </div>
          <!-- 如果没有实际支付金额，显示待支付 -->
          <div v-else style="display: flex; align-items: center; justify-content: flex-end; gap: 5px;">
            <span style="color: #E6A23C; font-weight: bold;">
              待支付: {{ scope.row.payable_amount }}
            </span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="附件" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.attachment_thumbnails && scope.row.attachment_thumbnails.length > 0" class="attachment-thumbnails">
            <el-popover
              v-for="(thumb, index) in scope.row.attachment_thumbnails"
              :key="thumb.id"
              placement="right"
              trigger="hover"
              width="400"
            >
              <img :src="thumb.url" style="width: 100%; max-height: 400px; object-fit: contain;">
              <img
                slot="reference"
                :src="thumb.url"
                :alt="thumb.filename"
                class="thumbnail-image"
                @click="previewImage(scope.row.attachment_thumbnails, index)"
              >
            </el-popover>
          </div>
          <i v-else-if="scope.row.has_attachments" class="el-icon-paperclip" style="font-size: 18px; color: #409EFF;" />
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>

      <el-table-column label="支付方式" width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.payment_method">{{ getPaymentMethodLabel(scope.row.payment_method) }}</span>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>

      <el-table-column label="发票状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.invoice_status" size="small" :type="scope.row.invoice_status === 'received' ? 'success' : (scope.row.invoice_status === 'issued' ? 'warning' : 'info')">
            {{ scope.row.invoice_status_display }}
          </el-tag>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>

      <el-table-column label="支付状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.payment_status === 'paid' ? 'success' : 'warning'">
            {{ scope.row.payment_status_display }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="预计付款日期" width="120" align="center">
        <template slot-scope="scope">
          <span :style="getDateStyle(scope.row.expected_payment_date)">
            {{ scope.row.expected_payment_date || '-' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            v-if="scope.row.payment_status === 'pending'"
            size="mini"
            type="primary"
            @click="handlePay(scope.row)"
          >
            标记已付款
          </el-button>
          <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
          <el-button
            v-if="scope.row.payment_status === 'pending'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="total > 0"
      background
      class="mt-pagination"
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 标记已付款对话框 -->
    <el-dialog title="标记已付款" :visible.sync="payDialogVisible" width="500px">
      <el-form ref="payForm" :model="payForm" :rules="payRules" label-width="120px">
        <el-form-item label="实际付款日期" prop="actual_payment_date">
          <el-date-picker
            v-model="payForm.actual_payment_date"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="payment_method">
          <el-select v-model="payForm.payment_method" placeholder="请选择" style="width: 100%;">
            <el-option label="银行转账" value="bank_transfer" />
            <el-option label="信用证" value="letter_of_credit" />
            <el-option label="PayPal" value="paypal" />
            <el-option label="西联汇款" value="western_union" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
            <el-option label="1688" value="1688" />
            <el-option label="淘宝" value="taobao" />
            <el-option label="现金" value="cash" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易流水号">
          <el-input v-model="payForm.reference_number" placeholder="银行流水号或第三方交易号" />
        </el-form-item>
        <el-form-item label="付款备注">
          <el-input v-model="payForm.payment_notes" type="textarea" :rows="3" placeholder="填写付款相关备注" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="payLoading" @click="confirmPay">确定</el-button>
      </span>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="应付账单详情" :visible.sync="viewDialogVisible" width="900px">
      <div v-if="viewDetail" class="detail-container">
        <!-- 头部：付款项目和状态 -->
        <div style="background: #f5f7fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>
              <div style="font-size: 18px; font-weight: bold; color: #303133; margin-bottom: 8px;">
                {{ viewDetail.notes || '未填写付款项目' }}
              </div>
              <div style="color: #909399; font-size: 13px;">
                {{ viewDetail.transaction_type }} · {{ viewDetail.transaction_date }}
              </div>
            </div>
            <div style="text-align: right;">
              <el-tag :type="viewDetail.payment_status === 'paid' ? 'success' : 'warning'" size="medium">
                {{ viewDetail.payment_status === 'paid' ? '已支付' : '待支付' }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 金额信息卡片 -->
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="12">
            <div style="border: 1px solid #EBEEF5; border-radius: 8px; padding: 20px; height: 100%;">
              <div style="color: #909399; font-size: 13px; margin-bottom: 8px;">应付金额</div>
              <div style="font-size: 28px; font-weight: bold; color: #E6A23C;">
                {{ viewDetail.payable_amount || viewDetail.amount }} <span style="font-size: 16px;">{{ viewDetail.currency }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div style="border: 1px solid #EBEEF5; border-radius: 8px; padding: 20px; height: 100%;">
              <div style="color: #909399; font-size: 13px; margin-bottom: 8px;">实际支付</div>
              <div
                v-if="viewDetail.amount"
                style="font-size: 28px; font-weight: bold;"
                :style="{
                  color: viewDetail.payable_amount && parseFloat(viewDetail.amount) === parseFloat(viewDetail.payable_amount) ? '#67C23A' : (viewDetail.payable_amount ? '#F56C6C' : '#409EFF')
                }"
              >
                {{ viewDetail.amount }} <span style="font-size: 16px;">{{ viewDetail.currency }}</span>
              </div>
              <div v-else style="font-size: 28px; color: #C0C4CC; font-weight: bold;">-</div>
            </div>
          </el-col>
        </el-row>

        <!-- 基本信息 -->
        <el-divider content-position="left"><i class="el-icon-document" /> 基本信息</el-divider>
        <el-row :gutter="20" style="margin-bottom: 15px;">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">供应商：</span>
              <span class="info-value">{{ viewDetail.supplier ? viewDetail.supplier.name : '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">关联订单：</span>
              <el-link v-if="viewDetail.order && viewDetail.order.order_no" type="primary" @click="viewOrder(viewDetail.order.id)">
                {{ viewDetail.order.order_no }}
              </el-link>
              <span v-else class="info-value">-</span>
            </div>
          </el-col>
        </el-row>

        <!-- 支付信息 -->
        <el-divider content-position="left"><i class="el-icon-bank-card" /> 支付信息</el-divider>
        <el-row :gutter="20" style="margin-bottom: 15px;">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">支付方式：</span>
              <span class="info-value">{{ viewDetail.payment_method ? getPaymentMethodLabel(viewDetail.payment_method) : '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">交易流水号：</span>
              <span class="info-value">{{ viewDetail.reference_number || '-' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-bottom: 15px;">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">实际付款日期：</span>
              <span class="info-value">{{ viewDetail.actual_payment_date || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">预计付款日期：</span>
              <span class="info-value">{{ viewDetail.expected_payment_date || '-' }}</span>
            </div>
          </el-col>
        </el-row>

        <!-- 发票信息 -->
        <el-divider content-position="left"><i class="el-icon-tickets" /> 发票信息</el-divider>
        <div v-if="viewDetail.invoice_required">
          <el-row :gutter="20" style="margin-bottom: 15px;">
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">发票状态：</span>
                <el-tag v-if="viewDetail.invoice_status" size="small" :type="viewDetail.invoice_status === 'received' ? 'success' : (viewDetail.invoice_status === 'issued' ? 'warning' : 'info')">
                  {{ viewDetail.invoice_status === 'received' ? '已收票' : (viewDetail.invoice_status === 'issued' ? '已开票' : '待开票') }}
                </el-tag>
                <span v-else class="info-value">-</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">发票类型：</span>
                <span class="info-value">{{ viewDetail.invoice_type || '-' }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-bottom: 15px;">
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">发票号码：</span>
                <span class="info-value">{{ viewDetail.invoice_number || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">开票日期：</span>
                <span class="info-value">{{ viewDetail.invoice_date || '-' }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-bottom: 15px;">
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">税率：</span>
                <span class="info-value">{{ viewDetail.tax_rate ? (viewDetail.tax_rate + '%') : '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">税额：</span>
                <span class="info-value">{{ viewDetail.tax_amount ? (viewDetail.tax_amount + ' ' + viewDetail.currency) : '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
        <div v-else style="color: #909399; padding: 10px 0;">
          不需要发票
        </div>

        <!-- 附件区域 -->
        <div v-if="viewDetail.attachments && viewDetail.attachments.length > 0">
          <el-divider content-position="left"><i class="el-icon-paperclip" /> 附件 ({{ viewDetail.attachments.length }})</el-divider>
          <div style="display: flex; flex-wrap: wrap; gap: 15px;">
            <div v-for="file in viewDetail.attachments" :key="file.id" style="text-align: center;">
              <el-image
                v-if="file.url && (file.filename.toLowerCase().endsWith('.jpg') || file.filename.toLowerCase().endsWith('.png') || file.filename.toLowerCase().endsWith('.jpeg'))"
                :src="file.url"
                :preview-src-list="viewDetail.attachments.filter(f => f.url && (f.filename.toLowerCase().endsWith('.jpg') || f.filename.toLowerCase().endsWith('.png') || f.filename.toLowerCase().endsWith('.jpeg'))).map(f => f.url)"
                fit="cover"
                style="width: 120px; height: 120px; border-radius: 8px; cursor: pointer; border: 1px solid #EBEEF5;"
              />
              <div style="margin-top: 8px; font-size: 12px; color: #606266; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" :title="file.filename">
                {{ file.filename }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 快速添加供应商对话框 -->
    <el-dialog title="快速添加供应商" :visible.sync="quickAddSupplierVisible" width="400px">
      <el-form ref="quickSupplierForm" :model="quickSupplierForm" :rules="quickSupplierRules" label-width="100px">
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="quickSupplierForm.name" placeholder="请输入供应商名称" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="quickAddSupplierVisible = false">取消</el-button>
        <el-button type="primary" :loading="quickSupplierLoading" @click="confirmQuickAddSupplier">确定</el-button>
      </span>
    </el-dialog>

    <!-- 创建应付账单对话框 -->
    <el-dialog title="创建应付账单" :visible.sync="createDialogVisible" width="600px">
      <el-form ref="createForm" :model="createForm" :rules="createRules" label-width="120px">
        <el-form-item label="付款项目" prop="notes">
          <el-input v-model="createForm.notes" placeholder="请输入付款项目名称（如：采购原材料、运费、服务费等）" />
        </el-form-item>
        <el-form-item label="供应商">
          <div style="display: flex; gap: 10px;">
            <el-select
              v-model="createForm.supplier_id"
              placeholder="请选择供应商（可选）"
              filterable
              clearable
              style="flex: 1;"
              @change="handleCreateSupplierChange"
            >
              <el-option
                v-for="supplier in suppliers"
                :key="supplier.id"
                :label="supplier.name"
                :value="supplier.id"
              />
            </el-select>
            <el-button type="primary" icon="el-icon-plus" @click="showQuickAddSupplier">快速添加</el-button>
          </div>
        </el-form-item>
        <el-form-item label="关联订单">
          <el-input v-model="createForm.order_id" placeholder="输入订单ID（可选）" />
        </el-form-item>
        <el-form-item label="账单类型">
          <el-input v-model="createForm.transaction_type" placeholder="如：采购付款、运费等" />
        </el-form-item>
        <el-form-item label="应付金额" prop="payable_amount">
          <el-input v-model="createForm.payable_amount" type="number" placeholder="输入应付金额">
            <el-select slot="append" v-model="createForm.currency" style="width: 100px;">
              <el-option label="CNY" value="CNY" />
              <el-option label="USD" value="USD" />
              <el-option label="EUR" value="EUR" />
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="预计付款日期">
          <el-date-picker
            v-model="createForm.expected_payment_date"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="收款账号">
          <el-select
            v-model="createForm.supplier_bank_account_id"
            placeholder="选择供应商收款账号"
            filterable
            clearable
            style="width: 100%;"
            @change="handleCreateBankAccountChange"
          >
            <el-option
              v-for="account in createSupplierBankAccounts"
              :key="account.id"
              :label="`${account.bank_name} - ${account.account_number.substr(-4)}`"
              :value="account.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>{{ account.bank_name }} - {{ account.account_number.substr(-4) }}</span>
                <el-tag v-if="account.is_default" size="mini" type="success">默认</el-tag>
              </div>
            </el-option>
          </el-select>
          <div style="margin-top: 8px;">
            <el-button type="text" size="small" @click="showCreateAddBankAccountDialog">
              <i class="el-icon-plus" /> 添加新收款账号
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="收款账号" style="margin-bottom: 0;">
          <el-input v-model="createForm.payee_account" placeholder="收款账号（自动填充）" disabled />
        </el-form-item>
        <el-form-item label="开户银行">
          <el-input v-model="createForm.payee_bank" placeholder="开户银行（自动填充）" disabled />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="createLoading" @click="confirmCreate">创建</el-button>
      </span>
    </el-dialog>

    <!-- 编辑付款信息抽屉 -->
    <el-drawer
      title="完善付款信息"
      :visible.sync="editDrawerVisible"
      :before-close="handleEditDrawerClose"
      size="80%"
      :wrapper-closable="false"
    >
      <div class="edit-drawer-content-split">
        <!-- 左侧：编辑表单 (60%) -->
        <div class="left-panel-form">
          <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="130px">
            <!-- 基本信息 + 支付信息 -->
            <div class="form-section">
              <div class="section-title">基本信息</div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="供应商">
                    <span>{{ editForm.supplier_name }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="应付金额">
                    <span style="font-size: 18px; font-weight: bold; color: #E6A23C;">
                      {{ editForm.payable_amount || editForm.amount }} {{ editForm.currency }}
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="付款项目">
                    <el-input v-model="editForm.notes" placeholder="付款项目名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="支付状态">
                    <el-select v-model="editForm.payment_status" style="width: 100%;">
                      <el-option label="待付款" value="pending" />
                      <el-option label="已付款" value="paid" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 收款账号信息 -->
            <div class="form-section" style="background: #f9fafc; padding: 15px; border-radius: 4px; margin-bottom: 20px;">
              <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div class="section-title" style="margin-bottom: 0;">
                  <i class="el-icon-bank-card" style="color: #409EFF; margin-right: 5px;" />
                  收款账号信息
                </div>
                <el-select
                  v-if="editSupplierBankAccounts.length > 0"
                  v-model="editSelectedBankAccountId"
                  placeholder="切换查看其他账号"
                  size="small"
                  style="width: 280px;"
                  @change="handleEditBankAccountChange"
                >
                  <el-option
                    v-for="account in editSupplierBankAccounts"
                    :key="account.id"
                    :label="`${account.bank_name} - ${account.account_number.substr(-4)}`"
                    :value="account.id"
                  >
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                      <span>{{ account.bank_name }} - {{ account.account_number.substr(-4) }}</span>
                      <el-tag v-if="account.is_default" size="mini" type="success">默认</el-tag>
                    </div>
                  </el-option>
                </el-select>
              </div>
              <div v-if="editForm.bank_account_info" style="padding-left: 10px;">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="info-item" style="margin-bottom: 10px;">
                      <span style="color: #909399; font-size: 13px;">账户名称：</span>
                      <span style="font-weight: 500;">{{ editForm.bank_account_info.account_name || '-' }}</span>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="info-item" style="margin-bottom: 10px;">
                      <span style="color: #909399; font-size: 13px;">开户银行：</span>
                      <span style="font-weight: 500;">{{ editForm.bank_account_info.bank_name || '-' }}</span>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="info-item" style="margin-bottom: 10px;">
                      <span style="color: #909399; font-size: 13px;">收款账号：</span>
                      <span style="font-weight: 500; font-family: monospace;">{{ editForm.bank_account_info.account_number || '-' }}</span>
                      <el-button
                        v-if="editForm.bank_account_info.account_number"
                        type="text"
                        size="mini"
                        icon="el-icon-document-copy"
                        @click="copyToClipboard(editForm.bank_account_info.account_number, '账号')"
                      />
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="info-item" style="margin-bottom: 10px;">
                      <span style="color: #909399; font-size: 13px;">账户类型：</span>
                      <span>{{ editForm.bank_account_info.account_type === 'corporate' ? '对公账户' : '个人账户' }}</span>
                    </div>
                  </el-col>
                </el-row>
                <el-row v-if="editForm.bank_account_info.payment_qrcode" :gutter="20">
                  <el-col :span="24">
                    <div class="info-item" style="margin-bottom: 10px;">
                      <span style="color: #909399; font-size: 13px;">收款二维码：</span>
                      <div style="margin-top: 10px;">
                        <el-image
                          :src="editForm.bank_account_info.payment_qrcode"
                          :preview-src-list="[editForm.bank_account_info.payment_qrcode]"
                          fit="contain"
                          style="width: 150px; height: 150px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;"
                        >
                          <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline" />
                          </div>
                        </el-image>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <div v-else style="color: #909399; text-align: center; padding: 20px;">
                <i class="el-icon-info" /> 暂无收款账号信息
              </div>
            </div>

            <!-- 支付信息 -->
            <div class="form-section">
              <div class="section-title">支付信息</div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="支付方式">
                    <el-select v-model="editForm.payment_method" placeholder="请选择" style="width: 100%;">
                      <el-option label="银行转账" value="bank_transfer" />
                      <el-option label="信用证" value="letter_of_credit" />
                      <el-option label="PayPal" value="paypal" />
                      <el-option label="西联汇款" value="western_union" />
                      <el-option label="支付宝" value="alipay" />
                      <el-option label="微信支付" value="wechat" />
                      <el-option label="1688" value="1688" />
                      <el-option label="淘宝" value="taobao" />
                      <el-option label="现金" value="cash" />
                      <el-option label="其他" value="other" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="支付流水号">
                    <el-input v-model="editForm.transaction_no" placeholder="银行流水号或第三方交易号" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="实际付款日期">
                    <el-date-picker
                      v-model="editForm.actual_payment_date"
                      type="date"
                      placeholder="选择日期"
                      style="width: 100%;"
                      value-format="yyyy-MM-dd"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="应付金额">
                    <el-input
                      v-model.number="editForm.payable_amount"
                      type="number"
                      placeholder="应付金额/需要支付的金额"
                      style="width: 100%;"
                    >
                      <template slot="append">{{ editForm.currency }}</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="实际支付金额">
                    <el-input
                      v-model.number="editForm.amount"
                      type="number"
                      placeholder="实际支付的金额"
                      style="width: 100%;"
                    >
                      <template slot="append">{{ editForm.currency }}</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 附件上传 -->
            <div class="form-section">
              <div class="section-title">附件上传</div>
              <el-form-item label="支付截图">
                <div
                  class="payment-upload-container"
                  tabindex="0"
                  @paste="handlePaymentPaste"
                >
                  <el-upload
                    ref="paymentUpload"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :data="uploadData"
                    list-type="picture-card"
                    :file-list="paymentScreenshots"
                    :on-success="handlePaymentScreenshotSuccess"
                    :on-remove="handlePaymentScreenshotRemove"
                    :before-upload="handleBeforePaymentUpload"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                </div>
                <el-button
                  v-if="paymentScreenshots.length > 0 && !paymentOcrProgress.show"
                  type="primary"
                  size="small"
                  icon="el-icon-magic-stick"
                  :loading="paymentOcrProgress.show"
                  style="margin-top: 10px; background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                  @click="handleManualExtractPayment"
                >
                  提取支付信息
                </el-button>
                <div v-if="paymentOcrProgress.show" class="ocr-progress">
                  <i class="el-icon-loading" /> {{ paymentOcrProgress.message }}
                </div>
              </el-form-item>
              <el-form-item label="发票截图">
                <div
                  class="invoice-upload-container"
                  tabindex="0"
                  @paste="handleInvoicePaste"
                >
                  <el-upload
                    ref="invoiceUpload"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :data="uploadData"
                    list-type="picture-card"
                    :file-list="invoiceScreenshots"
                    :on-success="handleInvoiceScreenshotSuccess"
                    :on-remove="handleInvoiceScreenshotRemove"
                    :before-upload="handleBeforeInvoiceUpload"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                  <div class="upload-tip">
                    <i class="el-icon-info" />
                    支持点击上传或粘贴图片（Ctrl+V），上传后自动识别发票信息
                  </div>
                </div>
                <el-progress
                  v-if="invoiceOcrProgress.show"
                  :percentage="invoiceOcrProgress.percentage"
                  :status="invoiceOcrProgress.status"
                  :stroke-width="8"
                  style="margin-top: 10px;"
                >
                  <template slot="default" slot-scope="scope">
                    {{ invoiceOcrProgress.text }}
                  </template>
                </el-progress>
                <el-button
                  v-if="invoiceScreenshots.length > 0 && !invoiceOcrProgress.show"
                  type="primary"
                  size="small"
                  icon="el-icon-magic-stick"
                  :loading="invoiceOcrProgress.show"
                  style="margin-top: 10px; background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                  @click="handleManualExtractInvoice"
                >
                  提取发票信息
                </el-button>
              </el-form-item>
            </div>

            <!-- 发票信息 -->
            <div class="form-section">
              <div class="section-title">发票信息</div>
              <el-form-item label="是否需要发票">
                <el-switch v-model="editForm.invoice_required" />
              </el-form-item>
              <template v-if="editForm.invoice_required">
                <el-form-item label="发票类型">
                  <el-select v-model="editForm.invoice_type" placeholder="请选择" style="width: 100%;">
                    <el-option label="增值税专用发票" value="vat_special" />
                    <el-option label="增值税普通发票" value="vat_normal" />
                    <el-option label="普通发票" value="normal" />
                  </el-select>
                </el-form-item>
                <el-form-item label="发票号码">
                  <el-input v-model="editForm.invoice_number" placeholder="发票号码" />
                </el-form-item>
                <el-form-item label="开票日期">
                  <el-date-picker
                    v-model="editForm.invoice_date"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%;"
                    value-format="yyyy-MM-dd"
                  />
                </el-form-item>
                <el-form-item label="发票状态">
                  <el-select v-model="editForm.invoice_status" placeholder="请选择" style="width: 100%;">
                    <el-option label="待开票" value="pending" />
                    <el-option label="已开票" value="issued" />
                    <el-option label="已收到" value="received" />
                  </el-select>
                </el-form-item>
              </template>
            </div>

            <!-- 税费信息 -->
            <div class="form-section">
              <div class="section-title">税费信息</div>
              <el-form-item label="税率 (%)">
                <el-input-number
                  v-model="editForm.tax_rate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  style="width: 100%;"
                />
              </el-form-item>
              <el-form-item label="税额">
                <el-input-number
                  v-model="editForm.tax_amount"
                  :min="0"
                  :precision="2"
                  style="width: 100%;"
                />
              </el-form-item>
            </div>

            <!-- 底部按钮 -->
            <div class="form-footer">
              <el-button @click="handleEditDrawerClose">取消</el-button>
              <el-button type="primary" :loading="editLoading" @click="confirmEdit">保存</el-button>
              <el-button
                v-if="editForm.payment_status !== 'paid'"
                type="success"
                :loading="editLoading"
                @click="markAsCompleted"
              >
                支付完成
              </el-button>
            </div>
          </el-form>
        </div>

        <!-- 右侧：AI 助手 (40%) -->
        <div class="right-panel-ai">
          <div class="ai-panel-header">
            <i class="el-icon-magic-stick" style="color: #1EB7E6;" />
            <span style="margin-left: 8px; font-weight: 600; font-size: 16px;">AI 财务助手</span>
          </div>

          <AIInnerChat
            ref="editAIChat"
            api-url="/crm/api/ai-payment-chat/"
            handler-name="payment_extractor"
            :context-data="editAIContext"
            :suggested-questions="editQuickActions"
            :auto-parse-json="true"
            :show-fill-button="true"
            placeholder="询问历史付款、收款账号，或补充付款信息..."
            @fill-form="handleEditAIFillForm"
            @json-parsed="handleEditAIJsonParsed"
          />
        </div>
      </div>
    </el-drawer>

    <!-- 订单详情对话框 -->
    <crm-order-detail
      :order_data="currentOrder"
      :order-states="orderStates"
      :show-able="orderDetailVisible"
      @close="orderDetailVisible=false"
    />

    <!-- 添加供应商收款账号对话框 -->
    <el-dialog
      title="添加供应商收款账号"
      :visible.sync="createBankAccountDialogVisible"
      width="600px"
      @close="handleCreateBankAccountDialogClose"
    >
      <el-form ref="createBankAccountForm" :model="createBankAccountForm" :rules="createBankAccountRules" label-width="120px">
        <el-form-item label="账户名称" prop="account_name">
          <el-input v-model="createBankAccountForm.account_name" placeholder="银行账户持有人名称" />
        </el-form-item>

        <el-form-item label="收款账号" prop="account_number">
          <el-input v-model="createBankAccountForm.account_number" placeholder="银行账号或支付宝账号" />
        </el-form-item>

        <el-form-item label="开户银行" prop="bank_name">
          <el-input v-model="createBankAccountForm.bank_name" placeholder="例如：中国工商银行、支付宝、微信支付" />
        </el-form-item>

        <el-form-item label="开户支行">
          <el-input v-model="createBankAccountForm.bank_branch" placeholder="具体支行名称（选填）" />
        </el-form-item>

        <el-form-item label="账户类型" prop="account_type">
          <el-select v-model="createBankAccountForm.account_type" style="width: 100%;">
            <el-option label="对公账户" value="corporate" />
            <el-option label="个人账户" value="personal" />
          </el-select>
        </el-form-item>

        <el-form-item label="币种">
          <el-select v-model="createBankAccountForm.currency" style="width: 100%;">
            <el-option label="人民币 (CNY)" value="CNY" />
            <el-option label="美元 (USD)" value="USD" />
            <el-option label="欧元 (EUR)" value="EUR" />
            <el-option label="英镑 (GBP)" value="GBP" />
          </el-select>
        </el-form-item>

        <el-form-item label="收款二维码">
          <el-upload
            ref="createBankAccountQrcodeUpload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="createBankAccountQrcodeUploadData"
            list-type="picture-card"
            :file-list="createBankAccountQrcodeList"
            :on-success="handleCreateBankAccountQrcodeSuccess"
            :on-remove="handleCreateBankAccountQrcodeRemove"
            :before-upload="beforeCreateBankAccountQrcodeUpload"
            :limit="1"
            accept="image/*"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <div style="color: #909399; font-size: 12px;">
            上传收款二维码（支持微信、支付宝、1688等）
          </div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="createBankAccountForm.notes" type="textarea" :rows="2" placeholder="其他说明信息（选填）" />
        </el-form-item>

        <el-form-item label="设为默认">
          <el-switch v-model="createBankAccountForm.is_default" />
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="createBankAccountDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="createBankAccountCreating" @click="confirmCreateCreateBankAccount">
          确认添加
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPayableList, markAsPaid, deletePayable, createPayable, getSuppliers, updatePayable, recognizeInvoice, recognizePayment, getPayableDetail, quickCreateSupplier } from '@/api/crm/payable'
import { Get as fetchOrder } from '@/api/crm/crmorder'
import { Get as GetOrderStates } from '@/api/crm/crmorderstate'
import { getSupplierBankAccounts, createSupplierBankAccount } from '@/api/crm/supplierBankAccount'
import AIInnerChat from '@/components/AIInnerChat'
import CrmOrderDetail from '@/views/crm/elements/crmorderdetail'
import { getToken } from '@/utils/auth'
import qs from 'qs'

export default {
  name: 'PayableList',
  components: {
    AIInnerChat,
    CrmOrderDetail
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        pagesize: 20,
        payment_status: '',
        supplier_id: '',
        kw: ''
      },
      statistics: {
        total_amount: '0.00',
        unpaid_amount: '0.00',
        unpaid_count: 0
      },
      suppliers: [],
      // 标记已付款
      payDialogVisible: false,
      payLoading: false,
      currentRow: null,
      payForm: {
        actual_payment_date: '',
        payment_method: '',
        reference_number: '',
        payment_notes: ''
      },
      payRules: {
        actual_payment_date: [{ required: true, message: '请选择付款日期', trigger: 'change' }],
        payment_method: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
      },
      // 创建账单
      createDialogVisible: false,
      createLoading: false,
      createForm: {
        order_id: '',
        supplier_id: '',
        supplier_bank_account_id: null, // 收款账号ID
        transaction_type: '采购付款',
        payable_amount: '',
        currency: 'CNY',
        expected_payment_date: '',
        payee_account: '',
        payee_bank: '',
        notes: ''
      },
      createRules: {
        notes: [{ required: true, message: '请输入付款项目名称', trigger: 'blur' }],
        payable_amount: [{ required: true, message: '请输入应付金额', trigger: 'blur' }]
      },
      // 快速添加供应商
      quickAddSupplierVisible: false,
      quickSupplierLoading: false,
      quickSupplierForm: {
        name: ''
      },
      quickSupplierRules: {
        name: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }]
      },
      // 查看详情
      viewDialogVisible: false,
      viewDetail: null,
      // 订单详情
      orderDetailVisible: false,
      currentOrder: {},
      orderStates: [],
      // 编辑付款信息
      editDrawerVisible: false,
      editLoading: false,
      editForm: {
        id: null,
        supplier_name: '',
        amount: '', // 实际支付金额
        currency: 'USD',
        notes: '',
        payment_status: 'pending',
        payment_method: '',
        transaction_no: '',
        actual_payment_date: new Date().toISOString().split('T')[0],
        payable_amount: null, // 应付金额
        invoice_required: false,
        invoice_type: '',
        invoice_number: '',
        invoice_date: '',
        invoice_status: 'pending',
        tax_rate: 0,
        tax_amount: 0
      },
      editRules: {
        notes: [{ required: true, message: '请输入付款项目', trigger: 'blur' }]
      },
      paymentScreenshots: [],
      invoiceScreenshots: [],
      invoiceOcrProgress: {
        show: false,
        message: '正在识别发票信息...'
      },
      paymentOcrProgress: {
        show: false,
        message: '正在识别支付信息...'
      },
      uploadData: {
        directory_name: 'payable_attachments',
        acl_type: '365' // 签名有效期365天（私有文件）
      },
      // 供应商收款账号管理
      createSupplierBankAccounts: [], // 创建对话框中供应商的收款账号列表
      editSupplierBankAccounts: [], // 编辑drawer中供应商的收款账号列表
      editSelectedBankAccountId: null, // 编辑drawer中选中的收款账号ID
      createBankAccountDialogVisible: false,
      createBankAccountCreating: false,
      createBankAccountForm: {
        account_name: '',
        account_number: '',
        bank_name: '',
        bank_branch: '',
        account_type: 'corporate',
        currency: 'CNY',
        notes: '',
        is_default: false
      },
      createBankAccountRules: {
        account_name: [{ required: true, message: '请输入账户名称', trigger: 'blur' }],
        account_number: [{ required: true, message: '请输入收款账号', trigger: 'blur' }],
        bank_name: [{ required: true, message: '请输入开户银行', trigger: 'blur' }],
        account_type: [{ required: true, message: '请选择账户类型', trigger: 'change' }]
      },
      createBankAccountQrcodeList: [], // 收款二维码文件列表
      createBankAccountQrcodeUploadData: {
        directory_name: 'supplier_bank_qrcodes',
        acl_type: '365'
      }
    }
  },
  computed: {
    uploadUrl() {
      // 使用通用文件上传接口
      return process.env.VUE_APP_BASE_API + '/crm/api/crmfile/'
    },
    uploadHeaders() {
      return {
        Authorization: getToken(),
        PTOKEN: this.$store.getters.projectId
      }
    },
    editAIContext() {
      if (!this.editForm.id) return {}
      return {
        payable_id: this.editForm.id,
        supplier_id: this.editForm.supplier?.id,
        supplier_name: this.editForm.supplier_name,
        amount: this.editForm.amount,
        currency: this.editForm.currency,
        payment_status: this.editForm.payment_status,
        current_date: new Date().toISOString().split('T')[0]
      }
    },
    editQuickActions() {
      return [
        {
          title: '历史付款',
          question: `请查询供应商"${this.editForm.supplier_name || '当前供应商'}"的历史付款情况，包括已付款金额、待付款金额、付款项目等详细信息`,
          icon: 'el-icon-document',
          color: '#409EFF'
        },
        {
          title: '收款账号',
          question: `请查询供应商"${this.editForm.supplier_name || '当前供应商'}"的所有收款账号信息，包括账号、开户行、币种等`,
          icon: 'el-icon-bank-card',
          color: '#67C23A'
        },
        {
          title: '补充流水号',
          question: '我想补充支付流水号和实际付款日期',
          icon: 'el-icon-document',
          color: '#409EFF'
        },
        {
          title: '添加发票信息',
          question: '我需要录入发票信息（发票号码、开票日期等）',
          icon: 'el-icon-tickets',
          color: '#67C23A'
        },
        {
          title: '标记已付款',
          question: '这笔款项已经支付完成，请帮我标记为已付款状态',
          icon: 'el-icon-check',
          color: '#E6A23C'
        }
      ]
    }
  },
  created() {
    this.getList()
    this.loadSuppliers()
    this.getOrderStates()
  },
  methods: {
    getList() {
      this.listLoading = true
      getPayableList(this.listQuery).then(response => {
        if (response.success) {
          this.list = response.data.list
          this.total = response.data.total
          this.statistics = response.data.statistics
        }
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    loadSuppliers() {
      getSuppliers().then(response => {
        if (response.success) {
          this.suppliers = response.data
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    async handleView(row) {
      // 加载详细信息
      try {
        const response = await getPayableDetail(row.id)
        if (response.success) {
          this.viewDetail = response.data
          this.viewDialogVisible = true
        } else {
          this.$message.error('加载详情失败')
        }
      } catch (error) {
        this.$message.error('加载详情失败: ' + (error.message || '未知错误'))
      }
    },
    previewImage(thumbnails, index) {
      // 使用 Element UI 的图片预览功能
      const urls = thumbnails.map(t => t.url)
      this.$alert(`<img src="${urls[index]}" style="width: 100%;">`, '图片预览', {
        dangerouslyUseHTMLString: true,
        showConfirmButton: false,
        closeOnClickModal: true,
        customClass: 'image-preview-dialog'
      })
    },
    handlePay(row) {
      this.currentRow = row
      this.payForm = {
        actual_payment_date: new Date().toISOString().substr(0, 10),
        payment_method: '',
        reference_number: '',
        payment_notes: ''
      }
      this.payDialogVisible = true
    },
    confirmPay() {
      this.$refs.payForm.validate(valid => {
        if (!valid) return

        this.payLoading = true
        markAsPaid(this.currentRow.id, this.payForm).then(response => {
          if (response.success) {
            this.$message.success('已标记为已付款')
            this.payDialogVisible = false
            this.getList()
          }
          this.payLoading = false
        }).catch(() => {
          this.payLoading = false
        })
      })
    },
    handleCreate() {
      this.createForm = {
        order_id: '',
        supplier_id: '',
        supplier_bank_account_id: null,
        transaction_type: '采购付款',
        payable_amount: '',
        currency: 'USD',
        expected_payment_date: '',
        payee_account: '',
        payee_bank: '',
        notes: ''
      }
      this.createSupplierBankAccounts = []
      this.createDialogVisible = true
    },
    // 显示快速添加供应商对话框
    showQuickAddSupplier() {
      this.quickSupplierForm.name = ''
      this.quickAddSupplierVisible = true
    },
    // 确认快速添加供应商
    confirmQuickAddSupplier() {
      this.$refs.quickSupplierForm.validate(valid => {
        if (!valid) return

        this.quickSupplierLoading = true
        quickCreateSupplier({
          name: this.quickSupplierForm.name
        }).then(response => {
          if (response.success) {
            this.$message.success(response.msg || '供应商添加成功')
            // 刷新供应商列表
            this.loadSuppliers()
            // 自动选中新添加的供应商
            this.createForm.supplier_id = response.data.id
            // 关闭对话框
            this.quickAddSupplierVisible = false
          }
          this.quickSupplierLoading = false
        }).catch(() => {
          this.quickSupplierLoading = false
        })
      })
    },
    confirmCreate() {
      this.$refs.createForm.validate(valid => {
        if (!valid) return

        this.createLoading = true
        createPayable(this.createForm).then(response => {
          if (response.success) {
            this.$message.success('创建成功')
            this.createDialogVisible = false
            this.getList()
          }
          this.createLoading = false
        }).catch(() => {
          this.createLoading = false
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除这个应付账单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePayable(row.id).then(response => {
          if (response.success) {
            this.$message.success('删除成功')
            this.getList()
          }
        })
      })
    },
    viewOrder(orderId) {
      if (!orderId) {
        this.$message.warning('订单ID不存在')
        return
      }

      // 获取订单详情并打开对话框
      const loading = this.$loading({
        lock: true,
        text: '加载订单详情...',
        spinner: 'el-icon-loading'
      })

      fetchOrder(orderId).then(response => {
        loading.close()
        console.log('fetchOrder 响应数据:', response)
        // 正确解析响应数据结构 - response 就是 {success, msg, data}
        if (response && response.success && response.data) {
          console.log('订单数据:', response.data)
          this.currentOrder = response.data
          this.orderDetailVisible = true
        } else {
          console.error('响应格式错误:', response)
          this.$message.error('获取订单详情失败')
        }
      }).catch(error => {
        loading.close()
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败: ' + (error.message || '网络错误'))
      })
    },
    // 获取订单状态选项
    getOrderStates() {
      GetOrderStates(null, qs.stringify({ all: '1' })).then(response => {
        if (response && response.data) {
          this.orderStates = response.data
        }
      }).catch(error => {
        console.error('获取订单状态失败:', error)
      })
    },
    getDateStyle(date) {
      if (!date) return {}
      const today = new Date().toISOString().substr(0, 10)
      if (date < today) {
        return { color: '#F56C6C', fontWeight: 'bold' }
      } else if (date === today) {
        return { color: '#E6A23C', fontWeight: 'bold' }
      }
      return {}
    },
    // 获取支付方式的中文标签
    getPaymentMethodLabel(value) {
      const methodMap = {
        'bank_transfer': '银行转账',
        'letter_of_credit': '信用证',
        'paypal': 'PayPal',
        'western_union': '西联汇款',
        'alipay': '支付宝',
        'wechat': '微信支付',
        '1688': '1688',
        'taobao': '淘宝',
        'cash': '现金',
        'other': '其他'
      }
      return methodMap[value] || value
    },
    // 编辑付款信息
    async handleEdit(row) {
      // 加载完整详情（包括发票、税费信息和附件）
      try {
        const detailResponse = await getPayableDetail(row.id)
        if (detailResponse.success) {
          const detail = detailResponse.data

          // 使用详情API返回的完整数据填充表单
          this.editForm = {
            id: detail.id,
            supplier_name: detail.supplier_name,
            amount: detail.amount, // 实际支付金额
            currency: detail.currency,
            notes: detail.notes || '',
            payment_status: detail.payment_status,
            payment_method: detail.payment_method || '',
            transaction_no: detail.reference_number || '',
            actual_payment_date: detail.actual_payment_date || new Date().toISOString().split('T')[0],
            payable_amount: detail.payable_amount || null, // 应付金额
            invoice_required: detail.invoice_required || false,
            invoice_type: detail.invoice_type || '',
            invoice_number: detail.invoice_number || '',
            invoice_date: detail.invoice_date || '',
            invoice_status: detail.invoice_status || 'pending',
            tax_rate: detail.tax_rate || 0,
            tax_amount: detail.tax_amount || 0,
            bank_account_info: detail.bank_account_info || null // 收款账号信息
          }

          // 处理附件
          if (detail.attachments && detail.attachments.length > 0) {
            // 将附件转换为el-upload需要的格式
            const attachments = detail.attachments.map(f => ({
              name: f.filename,
              url: f.url,
              uid: f.id
            }))

            // 暂时将所有附件都显示在发票截图中
            // TODO: 根据文件名或其他方式区分支付截图和发票截图
            this.invoiceScreenshots = attachments
            this.paymentScreenshots = []
          } else {
            this.paymentScreenshots = []
            this.invoiceScreenshots = []
          }

          // 加载供应商的所有收款账号
          if (detail.supplier && detail.supplier.id) {
            await this.loadEditSupplierBankAccounts(detail.supplier.id)
            // 设置当前选中的收款账号ID
            if (detail.bank_account_info) {
              this.editSelectedBankAccountId = detail.bank_account_info.id
            }
          }
        }
      } catch (error) {
        console.error('加载详情失败:', error)
        this.$message.error('加载详情失败: ' + (error.message || '未知错误'))
        return
      }

      this.editDrawerVisible = true
    },
    handleEditDrawerClose() {
      this.editDrawerVisible = false
      this.resetEditForm()
    },
    resetEditForm() {
      this.editForm = {
        id: null,
        supplier_name: '',
        amount: '',
        currency: 'USD',
        notes: '',
        payment_status: 'pending',
        payment_method: '',
        transaction_no: '',
        actual_payment_date: new Date().toISOString().split('T')[0],
        invoice_required: false,
        invoice_type: '',
        invoice_number: '',
        invoice_date: '',
        invoice_status: 'pending',
        tax_rate: 0,
        tax_amount: 0
      }
      this.paymentScreenshots = []
      this.invoiceScreenshots = []
      this.editSupplierBankAccounts = []
      this.editSelectedBankAccountId = null
    },
    confirmEdit() {
      this.$refs.editForm.validate(valid => {
        if (!valid) return

        this.savePayableData()
      })
    },
    // 自动保存数据（不关闭抽屉）
    autoSavePayableData() {
      this.savePayableData(false)
    },
    // 标记支付完成
    markAsCompleted() {
      this.$confirm('确定标记为支付完成吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 修改状态为已支付
        this.editForm.payment_status = 'paid'
        // 如果没有实际付款日期，设置为今天
        if (!this.editForm.actual_payment_date) {
          this.editForm.actual_payment_date = new Date().toISOString().split('T')[0]
        }
        // 保存并关闭
        this.savePayableData(true)
      }).catch(() => {})
    },
    // 保存应付账单数据
    savePayableData(closeDrawer = true) {
      this.editLoading = true

      // 如果状态是已支付但没有填实际支付金额，自动填充为应付金额
      let actualAmount = this.editForm.amount
      if (this.editForm.payment_status === 'paid' && !actualAmount) {
        actualAmount = this.editForm.payable_amount
        // 同步更新表单中的 amount 字段
        this.editForm.amount = actualAmount
      }

      const updateData = {
        notes: this.editForm.notes,
        payment_status: this.editForm.payment_status,
        payment_method: this.editForm.payment_method,
        transaction_no: this.editForm.transaction_no,
        actual_payment_date: this.editForm.actual_payment_date,
        amount: this.editForm.amount, // 实际支付金额
        payable_amount: this.editForm.payable_amount, // 应付金额
        invoice_required: this.editForm.invoice_required,
        invoice_type: this.editForm.invoice_type,
        invoice_number: this.editForm.invoice_number,
        invoice_date: this.editForm.invoice_date,
        invoice_status: this.editForm.invoice_status,
        tax_rate: this.editForm.tax_rate,
        // 确保tax_amount只保留2位小数
        tax_amount: this.editForm.tax_amount ? parseFloat(this.editForm.tax_amount.toFixed(2)) : 0,
        // 优先使用服务器返回的URL（response.data.url），而不是blob URL
        payment_screenshots: this.paymentScreenshots.map(f => f.response?.data?.url || f.url).filter(url => url && !url.startsWith('blob:')),
        invoice_screenshots: this.invoiceScreenshots.map(f => f.response?.data?.url || f.url).filter(url => url && !url.startsWith('blob:'))
      }

      console.log('保存的更新数据:', updateData)

      updatePayable(this.editForm.id, updateData).then(response => {
        if (response.success) {
          this.$message.success('保存成功')
          if (closeDrawer) {
            this.editDrawerVisible = false
            this.resetEditForm()
          }
          this.getList()
        }
        this.editLoading = false
      }).catch(() => {
        this.editLoading = false
      })
    },
    // AI 填充表单处理
    handleEditAIFillForm(data) {
      console.log('AI填充数据:', data)
      this.handleEditAIJsonParsed(data)
    },
    handleEditAIJsonParsed(jsonData) {
      console.log('解析的JSON数据:', jsonData)

      // 更新表单字段
      if (jsonData.payment_method) {
        this.editForm.payment_method = jsonData.payment_method
      }
      if (jsonData.transaction_no) {
        this.editForm.transaction_no = jsonData.transaction_no
      }
      if (jsonData.actual_payment_date) {
        this.editForm.actual_payment_date = jsonData.actual_payment_date
      }
      if (jsonData.payment_status) {
        this.editForm.payment_status = jsonData.payment_status
      }
      if (jsonData.invoice_number) {
        this.editForm.invoice_required = true
        this.editForm.invoice_number = jsonData.invoice_number
      }
      if (jsonData.invoice_type) {
        this.editForm.invoice_required = true
        this.editForm.invoice_type = jsonData.invoice_type
      }
      if (jsonData.invoice_date) {
        this.editForm.invoice_required = true
        this.editForm.invoice_date = jsonData.invoice_date
      }
      if (jsonData.invoice_status) {
        this.editForm.invoice_status = jsonData.invoice_status
      }
      if (jsonData.tax_rate !== undefined) {
        this.editForm.tax_rate = jsonData.tax_rate
      }
      if (jsonData.tax_amount !== undefined) {
        this.editForm.tax_amount = jsonData.tax_amount
      }
      if (jsonData.notes) {
        this.editForm.notes = jsonData.notes
      }

      this.$message.success('已从AI回复中提取并填充表单数据')
    },
    // 复制到剪贴板
    copyToClipboard(text, label) {
      if (!text) return
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success(`${label}已复制到剪贴板`)
        }).catch(() => {
          this.$message.error('复制失败，请手动复制')
        })
      } else {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = text
        document.body.appendChild(textArea)
        textArea.select()
        try {
          document.execCommand('copy')
          this.$message.success(`${label}已复制到剪贴板`)
        } catch (err) {
          this.$message.error('复制失败，请手动复制')
        }
        document.body.removeChild(textArea)
      }
    },
    // 文件上传处理
    handlePaymentScreenshotSuccess(response, file, fileList) {
      console.log('支付截图上传成功，响应数据:', response)

      if (response.success) {
        this.paymentScreenshots = fileList
        this.$message.success('上传成功')

        // 自动调用AI OCR识别支付信息
        const imageUrl = response.data?.url
        if (imageUrl && !imageUrl.startsWith('blob:')) {
          console.log('自动识别支付截图，URL:', imageUrl)
          this.recognizePayment(imageUrl)
        }
      } else {
        this.$message.error('上传失败: ' + (response.msg || '未知错误'))
      }
    },
    handlePaymentScreenshotRemove(file, fileList) {
      this.paymentScreenshots = fileList
    },
    handleInvoiceScreenshotSuccess(response, file, fileList) {
      console.log('发票上传成功，响应数据:', response)

      if (response.success) {
        this.invoiceScreenshots = fileList
        this.$message.success('上传成功')

        // 自动调用AI OCR识别发票信息
        // CRMFile接口返回格式: {success: true, msg: '', data: {id: xx, url: 'xxx', ...}}
        const imageUrl = response.data?.url
        console.log('提取的图片URL:', imageUrl)

        if (imageUrl) {
          this.recognizeInvoice(imageUrl)
        } else {
          console.warn('未能获取图片URL，响应数据:', response)
        }
      } else {
        this.$message.error('上传失败: ' + (response.msg || '未知错误'))
      }
    },
    handleInvoiceScreenshotRemove(file, fileList) {
      this.invoiceScreenshots = fileList
    },
    // 粘贴上传发票
    handleInvoicePaste(event) {
      const items = event.clipboardData?.items
      if (!items) return

      for (let i = 0; i < items.length; i++) {
        const item = items[i]
        if (item.type.indexOf('image') !== -1) {
          const file = item.getAsFile()
          if (file) {
            // 创建FormData上传
            const formData = new FormData()
            formData.append('file', file, `invoice_${Date.now()}.png`)

            this.$message.info('正在上传粘贴的发票图片...')

            // 直接上传
            this.$refs.invoiceUpload.handleStart(file)
            this.$refs.invoiceUpload.submit()
          }
          break
        }
      }
    },
    // 上传前处理
    handleBeforeInvoiceUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('图片大小不能超过 10MB!')
        return false
      }
      return true
    },
    // AI识别发票信息
    async recognizeInvoice(imageUrl) {
      this.invoiceOcrProgress.show = true
      this.invoiceOcrProgress.percentage = 20
      this.invoiceOcrProgress.status = ''
      this.invoiceOcrProgress.text = '正在识别发票信息...'

      try {
        const response = await recognizeInvoice({
          image_url: imageUrl
        })

        this.invoiceOcrProgress.percentage = 100
        this.invoiceOcrProgress.status = 'success'
        this.invoiceOcrProgress.text = '识别成功！'

        if (response.success) {
          const invoiceData = response.data

          // 自动填充发票信息
          if (invoiceData.invoice_number) {
            this.editForm.invoice_number = invoiceData.invoice_number
          }
          if (invoiceData.invoice_date) {
            this.editForm.invoice_date = invoiceData.invoice_date
          }
          if (invoiceData.invoice_type) {
            this.editForm.invoice_type = invoiceData.invoice_type
          }
          if (invoiceData.tax_rate !== undefined) {
            this.editForm.tax_rate = invoiceData.tax_rate
          }
          if (invoiceData.tax_amount !== undefined) {
            this.editForm.tax_amount = invoiceData.tax_amount
          }
          if (invoiceData.amount !== undefined) {
            // 如果识别出的金额与现有金额不一致，提示用户
            if (this.editForm.amount && invoiceData.amount !== this.editForm.amount) {
              this.$message.warning(`发票金额(${invoiceData.amount})与账单金额(${this.editForm.amount})不一致，请核对`)
            }
          }

          // 自动勾选需要发票
          this.editForm.invoice_required = true

          // 如果发票号码和发票日期都有了，自动设置为已开票
          if (this.editForm.invoice_number && this.editForm.invoice_date) {
            if (this.editForm.invoice_status === 'pending') {
              this.editForm.invoice_status = 'issued'
            }
          }

          this.$message.success('已自动填充发票信息')

          setTimeout(() => {
            this.invoiceOcrProgress.show = false
            // 自动保存数据
            this.autoSavePayableData()
          }, 2000)
        } else {
          this.invoiceOcrProgress.status = 'exception'
          this.invoiceOcrProgress.text = '识别失败：' + response.msg
          setTimeout(() => {
            this.invoiceOcrProgress.show = false
          }, 3000)
        }
      } catch (error) {
        console.error('发票识别失败:', error)
        this.invoiceOcrProgress.percentage = 100
        this.invoiceOcrProgress.status = 'exception'
        this.invoiceOcrProgress.text = '识别失败：' + (error.message || '网络错误')

        setTimeout(() => {
          this.invoiceOcrProgress.show = false
        }, 3000)
      }
    },
    // 手动提取发票信息
    handleManualExtractInvoice() {
      if (this.invoiceScreenshots.length === 0) {
        this.$message.warning('请先上传发票截图')
        return
      }

      // 获取最后一张上传的发票图片URL
      // 优先使用 response.data.url（服务器返回的实际URL），而不是 blob URL
      const lastInvoice = this.invoiceScreenshots[this.invoiceScreenshots.length - 1]
      const imageUrl = lastInvoice.response?.data?.url || lastInvoice.url

      console.log('发票对象:', lastInvoice)
      console.log('提取的URL:', imageUrl)

      if (!imageUrl) {
        this.$message.error('无法获取发票图片URL，请重新上传')
        return
      }

      // 检查是否是blob URL
      if (imageUrl.startsWith('blob:')) {
        this.$message.error('获取到的是临时URL，请确保文件已成功上传到服务器')
        return
      }

      console.log('手动提取发票信息，图片URL:', imageUrl)
      this.recognizeInvoice(imageUrl)
    },
    // 支付截图粘贴上传
    handlePaymentPaste(event) {
      const items = event.clipboardData?.items
      if (!items) return

      for (let i = 0; i < items.length; i++) {
        const item = items[i]
        if (item.type.indexOf('image') !== -1) {
          const file = item.getAsFile()
          if (file) {
            this.$message.info('正在上传粘贴的支付截图...')

            // 使用el-upload组件的方法上传
            this.$refs.paymentUpload.handleStart(file)
            this.$refs.paymentUpload.submit()
          }
          break
        }
      }
    },
    handleBeforePaymentUpload(file) {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.error('只能上传图片文件')
      }
      return isImage
    },
    // 手动提取支付信息
    handleManualExtractPayment() {
      if (this.paymentScreenshots.length === 0) {
        this.$message.warning('请先上传支付截图')
        return
      }

      const lastPayment = this.paymentScreenshots[this.paymentScreenshots.length - 1]
      const imageUrl = lastPayment.response?.data?.url || lastPayment.url

      if (!imageUrl) {
        this.$message.error('无法获取支付截图URL，请重新上传')
        return
      }

      if (imageUrl.startsWith('blob:')) {
        this.$message.error('获取到的是临时URL，请确保文件已成功上传到服务器')
        return
      }

      console.log('手动提取支付信息，图片URL:', imageUrl)
      this.recognizePayment(imageUrl)
    },
    // AI识别支付信息
    async recognizePayment(imageUrl) {
      this.paymentOcrProgress.show = true
      this.paymentOcrProgress.message = '正在识别支付信息...'

      try {
        const response = await recognizePayment({
          image_url: imageUrl
        })

        if (response.success && response.data) {
          const data = response.data
          console.log('AI识别的支付信息:', data)

          // 自动填充表单
          if (data.transaction_no) {
            this.editForm.transaction_no = data.transaction_no
          }
          if (data.payment_method) {
            // 将AI返回的支付方式映射到下拉选项
            const methodMap = {
              '微信支付': 'wechat',
              '支付宝': 'alipay',
              '银行转账': 'bank_transfer',
              'PayPal': 'paypal'
            }
            this.editForm.payment_method = methodMap[data.payment_method] || data.payment_method
          }
          if (data.payable_amount) {
            this.editForm.amount = parseFloat(data.payable_amount) // AI识别的金额作为实际支付金额
          }
          if (data.payment_time) {
            // 提取日期部分
            this.editForm.actual_payment_date = data.payment_time.split(' ')[0]
          }

          // 如果实际支付金额已填写，自动设置为已付款状态
          if (this.editForm.amount && this.editForm.payment_status !== 'paid') {
            this.editForm.payment_status = 'paid'
          }

          this.$message.success('支付信息识别成功')
          this.paymentOcrProgress.show = false

          // 自动保存数据
          this.$nextTick(() => {
            this.autoSavePayableData()
          })
        } else {
          throw new Error(response.msg || '识别失败')
        }
      } catch (error) {
        console.error('识别失败:', error)
        this.$message.error('识别失败: ' + (error.message || error.msg || '未知错误'))
        this.paymentOcrProgress.show = false
      }
    },
    // 供应商收款账号管理 - 编辑drawer
    // 加载编辑drawer中供应商的所有收款账号
    async loadEditSupplierBankAccounts(supplierId) {
      if (!supplierId) {
        this.editSupplierBankAccounts = []
        return
      }

      try {
        const response = await getSupplierBankAccounts({
          supplier_id: supplierId,
          is_active: true
        })
        if (response.success) {
          this.editSupplierBankAccounts = response.data
        }
      } catch (error) {
        console.error('加载收款账号失败:', error)
      }
    },
    // 切换查看其他收款账号
    handleEditBankAccountChange(accountId) {
      const account = this.editSupplierBankAccounts.find(acc => acc.id === accountId)
      if (account) {
        this.editForm.bank_account_info = {
          id: account.id,
          account_name: account.account_name,
          account_number: account.account_number,
          bank_name: account.bank_name,
          bank_branch: account.bank_branch,
          account_type: account.account_type,
          currency: account.currency,
          payment_qrcode: account.payment_qrcode,
          is_default: account.is_default
        }
      }
    },
    // 供应商收款账号管理 - 创建对话框
    // 当创建对话框中的供应商改变时，加载该供应商的收款账号
    async handleCreateSupplierChange(supplierId) {
      if (!supplierId) {
        this.createSupplierBankAccounts = []
        this.createForm.supplier_bank_account_id = null
        this.createForm.payee_account = ''
        this.createForm.payee_bank = ''
        return
      }

      try {
        const response = await getSupplierBankAccounts({
          supplier_id: supplierId,
          is_active: true
        })
        if (response.success) {
          this.createSupplierBankAccounts = response.data
          // 如果有默认账号，自动选中
          const defaultAccount = this.createSupplierBankAccounts.find(acc => acc.is_default)
          if (defaultAccount) {
            this.createForm.supplier_bank_account_id = defaultAccount.id
            this.handleCreateBankAccountChange(defaultAccount.id)
          }
        }
      } catch (error) {
        console.error('加载收款账号失败:', error)
      }
    },
    // 当选择收款账号时，自动填充账号和银行信息
    handleCreateBankAccountChange(accountId) {
      if (!accountId) {
        this.createForm.payee_account = ''
        this.createForm.payee_bank = ''
        return
      }

      const account = this.createSupplierBankAccounts.find(acc => acc.id === accountId)
      if (account) {
        this.createForm.payee_account = account.account_number
        this.createForm.payee_bank = account.bank_name
      }
    },
    // 显示添加收款账号对话框
    showCreateAddBankAccountDialog() {
      if (!this.createForm.supplier_id) {
        this.$message.warning('请先选择供应商')
        return
      }
      this.createBankAccountForm = {
        account_name: '',
        account_number: '',
        bank_name: '',
        bank_branch: '',
        account_type: 'corporate',
        currency: 'CNY',
        notes: '',
        is_default: false
      }
      this.createBankAccountQrcodeList = []
      this.createBankAccountDialogVisible = true
    },
    // 关闭添加收款账号对话框
    handleCreateBankAccountDialogClose() {
      this.createBankAccountDialogVisible = false
      this.$refs.createBankAccountForm && this.$refs.createBankAccountForm.resetFields()
      this.createBankAccountQrcodeList = []
    },
    // 确认创建收款账号
    confirmCreateCreateBankAccount() {
      this.$refs.createBankAccountForm.validate(async(valid) => {
        if (!valid) return

        this.createBankAccountCreating = true
        try {
          const accountData = {
            supplier_id: this.createForm.supplier_id,
            account_name: this.createBankAccountForm.account_name,
            account_number: this.createBankAccountForm.account_number,
            bank_name: this.createBankAccountForm.bank_name,
            bank_branch: this.createBankAccountForm.bank_branch,
            account_type: this.createBankAccountForm.account_type,
            currency: this.createBankAccountForm.currency,
            notes: this.createBankAccountForm.notes,
            is_default: this.createBankAccountForm.is_default,
            payment_qrcode: this.createBankAccountQrcodeList.length > 0
              ? (this.createBankAccountQrcodeList[0].response?.data?.url || this.createBankAccountQrcodeList[0].url)
              : ''
          }

          const response = await createSupplierBankAccount(accountData)
          if (response.success) {
            this.$message.success('收款账号添加成功')
            this.createBankAccountDialogVisible = false
            // 重新加载该供应商的收款账号列表
            await this.handleCreateSupplierChange(this.createForm.supplier_id)
            // 自动选中新添加的账号
            this.createForm.supplier_bank_account_id = response.data.id
            this.handleCreateBankAccountChange(response.data.id)
          }
        } catch (error) {
          console.error('创建收款账号失败:', error)
          this.$message.error('创建失败: ' + (error.message || error.msg || '未知错误'))
        } finally {
          this.createBankAccountCreating = false
        }
      })
    },
    // 收款二维码上传成功
    handleCreateBankAccountQrcodeSuccess(response, file, fileList) {
      if (response.success) {
        this.createBankAccountQrcodeList = fileList
        this.$message.success('二维码上传成功')
      } else {
        this.$message.error('上传失败: ' + (response.msg || '未知错误'))
      }
    },
    // 收款二维码移除
    handleCreateBankAccountQrcodeRemove(file, fileList) {
      this.createBankAccountQrcodeList = fileList
    },
    // 收款二维码上传前验证
    beforeCreateBankAccountQrcodeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!')
        return false
      }
      return true
    }
  }
}
</script>

<style scoped>
.mt-pagination {
  float: right;
  margin-top: 20px;
}

/* 详情对话框 */
.detail-container {
  padding: 0;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  line-height: 1.6;
}

.info-label {
  color: #909399;
  font-size: 14px;
  min-width: 100px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.attachment-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 编辑抽屉布局 */
.edit-drawer-content-split {
  display: flex;
  height: calc(100vh - 60px);
  gap: 20px;
  padding: 0 20px 20px 20px;
}

.left-panel-form {
  flex: 0 0 60%;
  overflow-y: auto;
  padding-right: 20px;
}

.right-panel-ai {
  flex: 0 0 40%;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #EBEEF5;
  padding-left: 20px;
  overflow: hidden;
  min-height: 0;
}

.ai-panel-header {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  padding: 10px 0;
  margin-bottom: 15px;
  border-bottom: 2px solid #1EB7E6;
}

.right-panel-ai ::v-deep .ai-inner-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.right-panel-ai ::v-deep .message-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.right-panel-ai ::v-deep .input-area {
  flex-shrink: 0;
  margin-top: 15px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #F5F7FA;
  border-radius: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.form-footer {
  position: sticky;
  bottom: 0;
  background-color: white;
  padding: 20px 0;
  border-top: 1px solid #EBEEF5;
  text-align: right;
  z-index: 10;
}

.invoice-upload-container,
.payment-upload-container {
  outline: none;
}

.invoice-upload-container:focus,
.payment-upload-container:focus {
  outline: 2px dashed #1EB7E6;
  outline-offset: 4px;
  border-radius: 4px;
}

.upload-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.upload-tip i {
  color: #1EB7E6;
}

/* 附件缩略图样式 */
.attachment-thumbnails {
  display: flex;
  gap: 5px;
  justify-content: center;
  align-items: center;
}

.thumbnail-image {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.thumbnail-image:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>
